package com.example.demo.delayQueue;

import cn.hutool.core.thread.ThreadFactoryBuilder;
import org.quartz.spi.ThreadExecutor;

import java.util.concurrent.*;

/**
 * @description: DelayQueue队列中每个元素都有一个过期时间，
 * 并且队列是个优先级队列，当从队列获取元素的时候，只有过期元素才会出队，
 * @author: cj
 * @create: 09-08-02 09:00:37
 */
public class DelayQueueDemo {
    private static DelayQueue queue = new DelayQueue ();
    private static ThreadFactory build = new ThreadFactoryBuilder ().setNamePrefix ( "" ).build ();
    private static ThreadPoolExecutor threadPoolExecutor =
            new ThreadPoolExecutor ( 1, 1, 0L, TimeUnit.MINUTES, queue
                    , build, new ThreadPoolExecutor.AbortPolicy () );

    public static void main(String[] args) {
        //延时15秒出队列
        MyDelay notice = new MyDelay ( 5000 );
        queue.add ( notice );
        threadPoolExecutor.submit ( new Runnable () {
            @Override
            public void run() {
                System.out.println ( "run" );
            }
        } );

        while (true) {
            try {
                //从延迟队列中取值,如果没有对象过期则取到null
                MyDelay delayedTask = (MyDelay) queue.poll ();
                if (delayedTask != null) {
                    threadPoolExecutor.execute ( delayedTask );
                }
            } catch (Exception e) {
                e.printStackTrace ();
            }
        }
    }
}
